﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using ZCrawler;
using Polenter.Serialization;

namespace ZCrawlerManager
{
    public static class TaskPool
    {
        public static List<Procedure> procedures;
        public static void Init()
        {
            procedures = new List<Procedure>();
            if (File.Exists("tasks.dat"))
            {
                try
                {
                    List<ZTask> tasks = ZBinaryWriter.Deserialize<List<ZTask>>("tasks.dat");
                    procedures = new List<Procedure>();
                    if(tasks!= null)
                    {
                        tasks.ForEach(t =>
                            {
                                t.Clean();
                                Procedure p = new Procedure();
                                p.task = t;
                                p.TaskID = t.TaskID;
                                procedures.Add(p);
                            });
                    }
                }
                catch (Exception)
                {
                    procedures = new List<Procedure>();
                }
            }
            else
            {
                procedures = new List<Procedure>();
            }
        }

        public static void Update()
        {
            List<ZTask> tasks = procedures.Select(p=>p.task).ToList();
            ZBinaryWriter.Serialize(tasks,"tasks_new.dat");
        }
        public static void Commit()
        {
            Update();
            File.Copy("tasks_new.dat", "tasks.dat",true);
        }
    }
}
